﻿#include "as_awaiter.h"



bool as::co::AcceptAwaiter::await_ready()
{
	return false;
}

void as::co::AcceptAwaiter::await_suspend(as::co::coroutine_handle handle)
{
	// 设置读事件处理器
	channel_->SetReadCoHandle(handle);
}

void as::co::AcceptAwaiter::await_resume()
{
	// 重置读事件处理器
	channel_->SetReadCoHandle(nullptr);

	if (!ready_)
	{
		as::net::Address addr;
		auto newfd = channel_->GetSocket()->accept(addr);
		if (newfd != SOCKET_ERR_FD)
		{
			socket_.set_fd(newfd);
			ready_ = true;
		}
	}
}

bool as::co::ReadAwaiter::await_ready()
{
	return false;
}

void as::co::ReadAwaiter::await_suspend(as::co::coroutine_handle handle)
{
	// 设置读事件处理器
	if(channel_.expired() == false)
		channel_.lock()->SetReadCoHandle(handle);
}

int as::co::ReadAwaiter::await_resume()
{
	if (channel_.expired() == false)
	{
		channel_.lock()->SetReadCoHandle(nullptr);
		TimeValue tv;
		ret_ = conn_->HandleRead(tv);
	}
	return ret_;
}

bool as::co::WriteAwaiter::await_ready()
{
	return false;
}

void as::co::WriteAwaiter::await_suspend(as::co::coroutine_handle handle)
{
	// 设置写事件处理器
	channel_->SetWriteCoHandle(handle);
}

int as::co::WriteAwaiter::await_resume()
{
	channel_->SetWriteCoHandle(nullptr);
	if (ready_ == false)
	{
		int canWriteCount = buf_->WriteableBytes();
		if (canWriteCount < 10240)
			buf_->gc();

		int ret = channel_->GetSocket()->write(buf_->GetWritePtr(), buf_->WriteableBytes());
		if (ret > 0)
		{
			return ret;
		}
	}
	return 0;

}
